const Koa = require('koa') // 1. 引入koa
const Router = require('koa-router')
const json = require('koa-json')
const logger = require('koa-logger')
const bodyparser = require('koa-bodyparser')
const koaJwt = require('koa-jwt')
const jwt  = require('jsonwebtoken')
const util = require('util')
const static = require('koa-static')
const app = new Koa() // 2. new一个koa对象
const router = new Router()
const secret = 'vue-campus'
const verify = util.promisify(jwt.verify)   // 解密
const upload = require('./server/config/getpath')
const sys_user = require('./server/controllers/sys_user')
const staff = require('./server/controllers/staff')
const product = require('./server/controllers/product')
const common_user = require('./server/controllers/common_user')
const category = require('./server/controllers/category')
const category_detail = require('./server/controllers/category_detail')
const order = require('./server/controllers/orderlist')
const banner_list = require('./server/controllers/banner')
const address = require('./server/controllers/address')
// allowedMethods 可有可无。
// 作用是当请求api的方法匹配的时候，会调用该方法。
// 比如应该是GET请求，而前端发起的是POST请求，此时就会调用该中间件方法
app.use(json());
app.use(logger());
app.use(bodyparser())
app.use(static(__dirname+'/public'));
// app.use(koaJwt({secret}).unless({
//   path: [/^\/api\/oauth\/token/]      // 数组路径不需要通过jwt验证
// }))
app.use(router.routes())
app.use(router.allowedMethods())
router.prefix = '/api'

// 系统用户登陆
router.post('/api/oauth/token', async (ctx, next) => {
  await sys_user.login(ctx)
})
// 获取系统用户信息
router.get('/api/sysUser/info', async (ctx, next) => {
  const token = ctx.header.authrization
  let payload
  if(token) {
    payload = await verify(token.split(' ')[1], secret)
    const data = await sys_user.getInfo(payload.name)
    ctx.body = {
      code: 0,
      message: '成功',
      data
    }
  }
})
// 普通用户登陆
router.post('/api/common/oauth/token', async (ctx, next) => {
  await common_user.login(ctx)
})
// 普通用户注册
router.post('/api/common/register', async (ctx) => {
  await common_user.register(ctx)
})
// 获取普通用户信息
router.get('/api/commonUser/info', async (ctx, next) => {
  const token = ctx.header.authrization
  console.log(token)
  let payload
  if(token) {
    payload = await verify(token.split(' ')[1], secret)
    const data = await common_user.getInfo(payload.name)
    ctx.body = {
      code: 0,
      message: '成功',
      data
    }
  }
})
// 修改普通用户信息
router.put('/api/commonUser/info/detail/update/:column', async (ctx) => {
  const token = ctx.header.authrization
  let payload
  if(token) {
    payload = await verify(token.split(' ')[1], secret)
    await common_user.updateInfo(payload.name,ctx)
  }
})
// 用户注册
router.post('/api/register', (ctx, next) => {
  user.register(ctx)
})
// 获取管理员员工
router.get('/api/staff', async (ctx) => {
  await staff.getStaffs(ctx)
})
// 根据搜索关键字获取员工
router.get('/api/staff/keywords', async (ctx) => {
  await staff.getStaffByKeyWords(ctx)
})
// 根据id获取管理员员工
router.get('/api/staff/:id',async (ctx, next) => {
  const data =  await staff.getStaffById(ctx.params.id)
  ctx.body = {
    code: 0,
    message: '成功',
    data
  }
})
// 根据id修改管理员员工
router.put('/api/staff/:id',async (ctx, next) => {
  const data = ctx.request.body
   await staff.updateStaff(data, ctx.params.id)
   ctx.body = {
    code: 0,
    message: '成功'
  }
})

// 新增管理员工
router.post('/api/staff',async (ctx, next) => {
  const data = ctx.request.body
  await staff.addStaff(data)
  ctx.body = {
    code: 0,
    message: '成功'
  }
})

// 根据id删除员工
router.delete('/api/staff/:id', async (ctx, next) => {
  const data = await staff.deleteStaff(ctx.params.id)
  ctx.body = {
    code: 0,
    message: '成功',
    data
  }
})

// 根据id更新员工状态
router.put('/api/staff/status/:id',async (ctx, next) => {
  const data = ctx.request.body
  await staff.updateStatus(data, ctx.params.id)
  ctx.body = {
    code: 0,
    message: '成功'
  }
})
// 获取全部商品
router.get('/api/product', async (ctx, next) => {
  await product.getProducts(ctx)
})
// 获取上架商品
router.get('/api/putawayProduct', async (ctx, next) => {
  await product.getStatusProducts(ctx)
})
// 获取热门商品
router.get('/api/hotProducts', async (ctx) => {
  await product.getHotProducts(ctx)
})
// 获取最新商品
router.get('/api/newProducts', async (ctx) => {
  await product.getNewProducts(ctx)
})
// 添加商品
router.post('/api/product', async (ctx) => {
  await product.addProduct(ctx)
})
// 上传商品图片
router.post('/api/file/upload', upload.single('file'), async (ctx) => {
  const filename = `http://localhost:8889/upload/${ctx.req.file.filename}`
  ctx.body = {
    filename: filename
  }
})
// 根据id获取商品
router.get('/api/product/:id', async (ctx) => {
  await product.getProductById(ctx)
})
// 根据搜索关键字获取商品
router.get('/api/products', async (ctx) => {
  await product.getProductsByKeyWords(ctx)
})
// 根据筛选条件获取商品
router.get('/api/products/filter', async (ctx) => {
  await product.getProductsByFilter(ctx)
})
// 根据id修改商品
router.put('/api/product/:id', async (ctx) => {
  await product.updateProduct(ctx)
})
// 根据id修改商品状态
router.put('/api/product/status/:id', async(ctx) => {
  await product.updateStatus(ctx)
})
// 根据id修改商品库存
router.put('/api/product/inventory/:id', async(ctx) => {
  await product.updateInventory(ctx)
})
// 根据商品类别获取销售量
router.get('/api/product/sale/:id', async(ctx) => {
  await product.getSaleByCategory(ctx)
})
// 根据商品类别获取商品
router.get('/api/products/:typeid', async (ctx) => {
  await product.getProductsByCategory(ctx)
})
// 获取商品类别
router.get('/api/categorys', async (ctx) => {
  await category.getCategorys(ctx)
})
// 获取商品类别
router.get('/api/category', async (ctx) => {
  await category.getCategory(ctx)
})
// 根据搜索关键字获取商品类别
router.get('/api/category/keywords', async (ctx) => {
  await category.getCategoryByKeyWords(ctx)
})
// 添加商品类别
router.post('/api/category/add', async (ctx) => {
  await category.addCategory(ctx)
})
// 根据id获取商品类别
router.get('/api/category/:id', async (ctx) => {
  await category.getCategoryById(ctx)
})
// 根据id修改商品类别
router.put('/api/category/update/:id', async (ctx) => {
  await category.updateCategoryById(ctx)
})
// 删除商品类别
router.put('/api/category/delete/:id', async (ctx) => {
  await category.deleteCategory(ctx)
})
// 获取商品类别明细
router.get('/api/categoryDetails', async (ctx) => {
  await category_detail.getCategoryDetails(ctx)
})
// 删除商品类别明细
router.put('/api/categoryDetail/delete/:id', async (ctx) => {
  await category_detail.deleteCategoryDetail(ctx)
})
// 根据关键字获取商品类别明细
router.get('/api/categoryDetails/keywords', async (ctx) => {
  await category_detail.getDetailByKeyWords(ctx)
})
// 根据id获取商品类别明细
router.get('/api/categoryDetail/:id', async (ctx) => {
  await category_detail.getCategoryDetailById(ctx)
})
// 添加商品明细
router.post('/api/categoryDetail/add', async (ctx) => {
  await category_detail.addCategoryDetail(ctx)
})
// 修改商品明细
router.put('/api/categoryDetail/update/:id', async (ctx) => {
  await category_detail.updateCategoryDetail(ctx)
})
// 获取全部普通用户
router.get('/api/commonUsers', async (ctx) => {
  await common_user.getCommonUsers(ctx)
})
// 根据id获取普通用户
router.get('/api/commonUser/:id', async (ctx) => {
  await common_user.getUserById(ctx)
})
// 根据关键字获取普通用户
router.get('/api/commonUsers/keywords', async (ctx) => {
  await common_user.getUserByKeyWords(ctx)
})
// 根据id修改普通用户状态
router.put('/api/commonUser/status/:id', async (ctx) => {
  await common_user.updateStatus(ctx)
})
// 修改普通用户余额
router.put('/api/commonUser/balance/update', async (ctx) => {
  const token = ctx.header.authrization
  let payload
  if(token) {
    payload = await verify(token.split(' ')[1], secret)
    await common_user.updateBalance(ctx, payload.name)
  }
})
// 修改密码
router.put('/api/commonUser/password/modify', async (ctx) => {
  const token = ctx.header.authrization
  let payload
  if(token) {
    payload = await verify(token.split(' ')[1], secret)
    await common_user.modifyPassword(ctx, payload.name)
  }
})
//设置支付密码
router.put('/api/commonUser/pay/password/modify', async (ctx) => {
  const token = ctx.header.authrization
  let payload
  if(token) {
    payload = await verify(token.split(' ')[1], secret)
    await common_user.modifyPayPassword(ctx, payload.name)
  }
})
// 获取全部订单
router.get('/api/orders', async (ctx) => {
  const token = ctx.header.authrization
  if(token) {
    await order.getOrders(ctx)
  }
})
// 获取全部订单
router.get('/api/allorders', async (ctx) => {
  const token = ctx.header.authrization
  if(token) {
    await order.getAllOrder(ctx)
  }
})
// 根据关键字获取订单
router.get('/api/orders/keywords', async (ctx) => {
  const token = ctx.header.authrization
  if(token) {
    await order.getOrderByKeyWords(ctx)
  }
})
// 根据id获取订单
router.get('/api/order/:id', async (ctx) => {
  const token = ctx.header.authrization
  if(token) {
    await order.getOrderById(ctx)
  }
})
// 创建订单
router.post('/api/order/add', async (ctx) => {
  const token = ctx.header.authrization
  if(token) {
    await order.addOrder(ctx)
  }
})
// 修改订单状态
router.put('/api/order/status/update/:id', async (ctx) => {
  const token = ctx.header.authrization
  if(token) {
    await order.updateOrderStatus(ctx)
  }
})
// 获取banner
router.get('/api/banners', async (ctx) => {
  await banner_list.getBanners(ctx)
})
// 根据id获取banner
router.get('/api/banner/:id', async (ctx) => {
  await banner_list.getBannerById(ctx)
})
// 添加banner
router.post('/api/banner/add', async (ctx) => {
  await banner_list.addBanner(ctx)
})
// 更新banner
router.put('/api/banner/update/:id', async (ctx) => {
  await banner_list.updateBanner(ctx)
})
// 添加地址
router.post('/api/address/add', async (ctx) => {
  await address.addAddress(ctx)
})
// 获取地址
router.get('/api/address/:id', async (ctx) => {
  await address.getAddress(ctx)
})
app.listen(8889, () => {
    console.log('start success. http://localhost:8889');
}); // 3.监听端口并启动